package com.kangzhili.nettypush.websocket;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket客户端连接管理器
 * 负责保存、查找、移除客户端Channel，实现点对点和广播推送
 */
public class WebSocketChannelManager {
    // 保存所有连接的Channel（可用于广播）
    private static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    // 用户ID与Channel的映射（点对点推送）
    private static final Map<String, Channel> userChannelMap = new ConcurrentHashMap<>();

    /**
     * 添加Channel到管理器
     */
    public static void add(Channel channel) {
        channelGroup.add(channel);
    }

    /**
     * 移除Channel
     */
    public static void remove(Channel channel) {
        channelGroup.remove(channel);
        userChannelMap.values().removeIf(ch -> ch.equals(channel));
    }

    /**
     * 绑定用户ID与Channel
     */
    public static void bindUser(String userId, Channel channel) {
        userChannelMap.put(userId, channel);
    }

    /**
     * 通过用户ID查找Channel
     */
    public static Channel getChannel(String userId) {
        return userChannelMap.get(userId);
    }

    /**
     * 广播消息到所有客户端
     */
    public static void broadcast(Object msg) {
        channelGroup.writeAndFlush(msg);
    }

    /**
     * 向指定用户推送消息
     */
    public static void pushToUser(String userId, Object msg) {
        Channel channel = getChannel(userId);
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(msg);
        }
    }
} 